package com.blockmeta.bbs.businesslibrary.net.interceptor;


import android.net.Uri;
import android.os.Build;
import android.text.TextUtils;
import com.blankj.utilcode.util.LogUtils;

import com.blankj.utilcode.util.LogUtils;
import com.blockmeta.bbs.baselibrary.base.app.BaseApp;
import com.blockmeta.bbs.baselibrary.provider.IApplicationProvider;
import com.blockmeta.bbs.baselibrary.utils.SharedPreferenceUtil;
import com.blockmeta.bbs.businesslibrary.arouter.RouterHelper;
import com.blockmeta.bbs.businesslibrary.arouter.RouterPath;
import com.blockmeta.bbs.businesslibrary.constant.Constant;
import com.blockmeta.bbs.businesslibrary.util.AccountHelper;
import com.blockmeta.bbs.businesslibrary.util.AppCode;
import com.blockmeta.bbs.businesslibrary.util.DeviceUtil;
import com.blockmeta.bbs.businesslibrary.util.GateWayUtil;
import com.blockmeta.bbs.businesslibrary.util.ReportIssue;

import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

/**
 * @author airthor
 * @date 2019/3/26
 * 通过拦截器为请求统一添加header
 */

public class AddHeaderInterceptor implements Interceptor {


    @Override
    public Response intercept(Chain chain) throws IOException {
        Request originalRequest = chain.request();
        String cacheControl = originalRequest.cacheControl().toString();
        String uid = "";
        if (AccountHelper.getUserPhonePOJO() != null && AccountHelper.getUid() != null
                && !TextUtils.isEmpty(AccountHelper.getUid())) {
            uid = AccountHelper.getUid();
        }
        String url = Uri.decode(originalRequest.url().toString());
        String time = String.valueOf((System.currentTimeMillis() / 1000L));

        LogUtils.d("request", "intercept: url:"+url+"time:"+time);
        IApplicationProvider provider = RouterHelper.getProvider(RouterPath.APPLICATION_PROVIDER);
        String myAppCode = AppCode.getMyAppCode(provider.getProjectBuildInfo().application_id);
        String gateToken = AccountHelper.getToken();
        Request.Builder requestBuilder = originalRequest.newBuilder()
                .header("Authorization", GateWayUtil.getGateAuth())
                .header("User-Agent",getUserAgent() + " " + myAppCode)
                .header("app_code", myAppCode)
                .header("authme",gateToken)
                .header("uid", uid)
                .header("from", "android")
                .header("device_id", DeviceUtil.getIMEI())
                .header("time",time)
                .method(originalRequest.method(), originalRequest.body());

        Request request = requestBuilder.build();


        long startTime=System.currentTimeMillis();   //获取开始时间
        Response originalResponse = chain.proceed(request);
        long endTime=System.currentTimeMillis(); //获取结束时间
        //记录请求时间
//        ReportIssue.recordHttpCostIssue((int) (endTime - startTime), originalResponse.code(), request.url().host(), request.url().encodedPath());
        Response.Builder responseBuilder =
                //Cache control设置缓存
                originalResponse.newBuilder().header("Cache-Control", cacheControl);
        LogUtils.i("author" + "http request:" + request.toString() + "response:" + originalResponse.toString());

        //插入内存内issues数据结构，并计数，当app进入后台的时候判断如果超过100条则上报
        return responseBuilder.build();
    }

    /**
     * MD5加密
     *
     * @param string 需要加密的
     * @return md5
     */
    public static String MD5(String string) {
        if (TextUtils.isEmpty(string)) {
            return "";
        }
        MessageDigest md5 = null;
        try {
            md5 = MessageDigest.getInstance("MD5");
            byte[] bytes = md5.digest(string.getBytes());
            StringBuilder result = new StringBuilder();
            for (byte b : bytes) {
                String temp = Integer.toHexString(b & 0xff);
                if (temp.length() == 1) {
                    temp = "0" + temp;
                }
                result.append(temp);
            }
            return result.toString();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return "";
    }

    private static String getUserAgent() {
        String userAgent = "";
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            try {
                userAgent = System.getProperty("http.agent");
            } catch (Exception e) {
                userAgent = System.getProperty("http.agent");
            }
        } else {
            userAgent = System.getProperty("http.agent");
        }
        StringBuffer sb = new StringBuffer();
        for (int i = 0, length = userAgent.length(); i < length; i++) {
            char c = userAgent.charAt(i);
            if (c <= '\u001f' || c >= '\u007f') {
                sb.append(String.format("\\u%04x", (int) c));
            } else {
                sb.append(c);
            }
        }
        return sb.toString();
    }
}
